package com.xm.concurrent.base;

import java.util.ConcurrentModificationException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 4.2.5 安全的终止线程
 *
 * @author xiaoming
 * @date 2021-05-23 13:20
 */
public class ShutdownThread {
    private static final Logger logger = Logger.getGlobal();

    public static void main(String[] args) throws InterruptedException {
        Runner one = new Runner();
        Thread countThread = new Thread(one, "CountThread");
        countThread.start();
        TimeUnit.SECONDS.sleep(2);

        countThread.interrupt();

        Runner tow = new Runner();
        countThread = new Thread(tow, "CountThread");
        countThread.start();

        TimeUnit.SECONDS.sleep(2);

        tow.cancel();
    }

    private static class Runner implements Runnable {
        private long i;
        private volatile boolean on = true;

        @Override
        public void run() {
            //  优雅退出
            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }

            logger.info("Count i = " + i);
        }
        public void cancel() {
            on = false;
        }
    }

}
